/**
 * 获取设备信息的主函数
 * 收集并返回设备的详细信息,包括硬件、软件、网络等各个方面
 * @returns {Object} 包含设备详细信息的对象
 */
export default function getDeviceInfo() {
    const deviceInfo = {
        // 基本信息
        userAgent: navigator.userAgent, // 用户代理字符串
        platform: navigator.platform, // 运行平台
        language: navigator.language, // 当前语言
        languages: navigator.languages || [navigator.language], // 支持的语言列表
        appVersion: navigator.appVersion, // 应用程序版本
        appName: navigator.appName, // 应用程序名称
        appCodeName: navigator.appCodeName, // 应用程序代码名称
        vendor: navigator.vendor, // 浏览器供应商
        product: navigator.product, // 产品名称
        
        // 在线状态
        online: navigator.onLine, // 是否在线
        
        // 屏幕信息
        screenWidth: window.innerWidth, // 窗口内部宽度
        screenHeight: window.innerHeight, // 窗口内部高度
        screenColorDepth: screen.colorDepth, // 屏幕颜色深度
        screenPixelDepth: screen.pixelDepth, // 屏幕像素深度
        documentWidth: document.documentElement.clientWidth, // 文档可见区域宽度
        documentHeight: document.documentElement.clientHeight, // 文档可见区域高度
        scrollWidth: document.documentElement.scrollWidth, // 文档完整宽度
        scrollHeight: document.documentElement.scrollHeight, // 文档完整高度
        
        // 硬件信息
        deviceMemory: navigator.deviceMemory || 'Unknown', // 设备内存大小
        cpuClass: navigator.cpuClass || 'Unknown', // CPU类型
        hardwareConcurrency: navigator.hardwareConcurrency || 'Unknown', // CPU核心数
        maxTouchPoints: navigator.maxTouchPoints || 0, // 最大触控点数
        batteryInfo: null, // 电池信息(后续异步获取)
        
        // 设备类型检测
        isMobile: /Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent), // 是否移动设备
        isTablet: /(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(navigator.userAgent.toLowerCase()), // 是否平板设备
        isDesktop: !(/Mobi|Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)), // 是否桌面设备
        isTouchDevice: ('ontouchstart' in window) || (navigator.maxTouchPoints > 0), // 是否触屏设备
        isBot: /bot|crawler|spider|crawling/i.test(navigator.userAgent), // 是否爬虫
        
        // 浏览器特性
        devicePixelRatio: window.devicePixelRatio, // 设备像素比
        cookieEnabled: navigator.cookieEnabled, // 是否启用cookie
        doNotTrack: navigator.doNotTrack || window.doNotTrack || navigator.msDoNotTrack, // 是否开启"请勿追踪"
        
        // API支持检测
        geolocation: 'geolocation' in navigator, // 地理位置API
        hasWebRTC: 'RTCPeerConnection' in window, // WebRTC支持
        hasLocalStorage: 'localStorage' in window, // 本地存储支持
        hasSessionStorage: 'sessionStorage' in window, // 会话存储支持
        hasIndexedDB: 'indexedDB' in window, // IndexedDB支持
        hasServiceWorker: 'serviceWorker' in navigator, // Service Worker支持
        hasWebSockets: 'WebSocket' in window, // WebSocket支持
        hasWebWorker: 'Worker' in window, // Web Worker支持
        hasSharedWorker: 'SharedWorker' in window, // Shared Worker支持
        mediaDevices: 'mediaDevices' in navigator, // 媒体设备API
        permissions: 'permissions' in navigator, // 权限API
        bluetooth: 'bluetooth' in navigator, // 蓝牙API
        usb: 'usb' in navigator, // USB API
        nfc: 'nfc' in navigator, // NFC API
        
        // 新增: 更多API支持检测
        hasWebAssembly: typeof WebAssembly === 'object', // WebAssembly支持
        hasWebGPU: 'gpu' in navigator, // WebGPU支持
        hasWebXR: 'xr' in navigator, // WebXR支持
        hasWebNFC: 'NDEFReader' in window, // Web NFC支持
        hasWebUSB: 'USB' in window, // Web USB支持
        hasWebBluetooth: 'Bluetooth' in window, // Web蓝牙支持
        hasWebMIDI: 'requestMIDIAccess' in navigator, // Web MIDI支持
        hasWebSerial: 'serial' in navigator, // Web串口支持
        hasWebHID: 'hid' in navigator, // Web HID支持
        hasCredentialManagement: 'credentials' in navigator, // 凭证管理API
        hasPaymentRequest: 'PaymentRequest' in window, // 支付请求API
        hasWebShare: 'share' in navigator, // Web分享API
        hasWebAuthentication: 'PublicKeyCredential' in window, // Web认证API
        
        // 图形和多媒体能力
        webgl: hasWebGL(), // WebGL支持
        canvas: hasCanvas(), // Canvas支持
        audio: hasAudio(), // 音频支持
        video: hasVideo(), // 视频支持
        
        // 性能信息
        performance: getPerformanceInfo(), // 性能相关信息
        
        // 时区信息
        timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, // 时区
        timezoneOffset: new Date().getTimezoneOffset(), // 时区偏移
        
        // 字体信息
        fonts: getFontInfo(), // 字体相关信息
        
        // WebGL详细信息
        webglInfo: getWebGLInfo(), // WebGL详细信息
        
        // 系统主题
        systemTheme: getSystemTheme(), // 系统主题设置
        
        // 输入设备信息
        inputDevices: getInputDevices(), // 输入设备信息
        
        // 浏览器功能支持
        browserFeatures: getBrowserFeatures(), // 浏览器特性支持
        
        // 安全信息
        security: getSecurityInfo(), // 安全相关信息

        // 高级硬件信息
        advancedHardware: {
            gpuTier: getGPUTier(), // GPU性能等级
            processorArchitecture: getProcessorArchitecture(), // 处理器架构
            virtualization: checkVirtualization(), // 虚拟化支持
            powerEfficiency: getPowerEfficiency() // 能效评估
        },

        // 网络质量检测
        networkQuality: {
            latency: measureLatency(), // 网络延迟
            bandwidth: estimateBandwidth(), // 带宽估算
            connectionQuality: assessConnectionQuality() // 连接质量评估
        },

        // 设备健康状态
        deviceHealth: {
            memoryUsage: getMemoryUsage(), // 内存使用情况
            cpuUsage: getCPUUsage(), // CPU使用情况
            thermalState: getThermalState(), // 温度状态
            batteryHealth: getBatteryHealth() // 电池健康状态
        },

        // 高级媒体能力
        mediaCapabilities: {
            supportedCodecs: getSupportedCodecs(), // 支持的编解码器
            maxResolution: getMaxSupportedResolution(), // 最大支持分辨率
            hdrSupport: checkHDRSupport(), // HDR支持
            audioFormats: getSupportedAudioFormats() // 支持的音频格式
        },

        // 辅助功能支持
        accessibility: {
            screenReader: detectScreenReader(), // 屏幕阅读器检测
            highContrast: detectHighContrast(), // 高对比度模式
            reducedMotion: checkReducedMotion(), // 减少动画模式
            colorBlindMode: detectColorBlindMode() // 色盲模式
        },

        // 安全特性
        advancedSecurity: {
            encryptionSupport: checkEncryptionSupport(), // 加密支持
            biometricCapabilities: getBiometricCapabilities(), // 生物识别能力
            secureElementPresent: checkSecureElement(), // 安全元件
            trustZoneSupport: checkTrustZone() // 可信执行环境
        }
    };

    // 网络信息
    if (navigator.connection) {
        const conn = navigator.connection;
        deviceInfo.network = {
            type: conn.type, // 网络类型
            effectiveType: conn.effectiveType, // 有效网络类型
            downlink: conn.downlink, // 下行速度
            downlinkMax: conn.downlinkMax, // 最大下行速度
            rtt: conn.rtt, // 往返时间
            saveData: conn.saveData, // 省流量模式
            bandwidth: conn.bandwidth || 'Unknown', // 带宽
            metered: conn.metered || 'Unknown', // 计费网络
            onchange: !!conn.onchange, // 网络变化事件支持
            // 高级网络信息
            throughput: measureNetworkThroughput(), // 网络吞吐量
            stability: assessNetworkStability(), // 网络稳定性
            qualityMetrics: getNetworkQualityMetrics() // 网络质量指标
        };
    }

    // 操作系统和浏览器详细信息
    const osInfo = getDetailedOS(); // 获取操作系统信息
    const browserInfo = getDetailedBrowser(); // 获取浏览器信息
    deviceInfo.os = osInfo;
    deviceInfo.browser = browserInfo;

    // 屏幕详细信息
    deviceInfo.screen = {
        width: screen.width, // 屏幕宽度
        height: screen.height, // 屏幕高度
        availWidth: screen.availWidth, // 可用宽度
        availHeight: screen.availHeight, // 可用高度
        colorDepth: screen.colorDepth, // 颜色深度
        pixelDepth: screen.pixelDepth, // 像素深度
        orientation: screen.orientation ? {
            type: screen.orientation.type, // 屏幕方向类型
            angle: screen.orientation.angle // 屏幕旋转角度
        } : 'Unknown',
        rotation: window.orientation || 0, // 屏幕旋转
        refreshRate: getScreenRefreshRate(), // 刷新率
        isExtended: window.screen.isExtended || false, // 是否扩展显示
        scaling: window.devicePixelRatio, // 缩放比例
        colorGamut: getColorGamut(), // 色域
        // 高级屏幕信息
        brightness: getScreenBrightness(), // 亮度
        contrast: getScreenContrast(), // 对比度
        hdrCapabilities: getHDRCapabilities(), // HDR能力
        touchResponseTime: measureTouchResponseTime() // 触摸响应时间
    };

    // 异步获取存储信息
    if (navigator.storage && navigator.storage.estimate) {
        navigator.storage.estimate().then(estimate => {
            deviceInfo.storage = {
                quota: formatBytes(estimate.quota), // 存储配额
                usage: formatBytes(estimate.usage), // 已用存储
                available: formatBytes(estimate.quota - estimate.usage), // 可用存储
                percentageUsed: ((estimate.usage / estimate.quota) * 100).toFixed(2) + '%', // 使用百分比
                persistent: estimate.persistent || false, // 持久存储
                temporary: estimate.temporary || false, // 临时存储
                // 存储性能指标
                readSpeed: measureStorageReadSpeed(), // 读取速度
                writeSpeed: measureStorageWriteSpeed(), // 写入速度
                reliability: assessStorageReliability() // 可靠性评估
            };
        });
    }

    // 异步获取电池信息
    if (navigator.getBattery) {
        navigator.getBattery().then(battery => {
            deviceInfo.batteryInfo = {
                charging: battery.charging, // 是否充电
                level: battery.level * 100 + '%', // 电量百分比
                chargingTime: battery.chargingTime === Infinity ? 'Unknown' : battery.chargingTime, // 充电时间
                dischargingTime: battery.dischargingTime === Infinity ? 'Unknown' : battery.dischargingTime, // 放电时间
                temperature: battery.temperature || 'Unknown', // 电池温度
                voltage: battery.voltage || 'Unknown', // 电池电压
                health: battery.health || 'Unknown', // 电池健康状况
                // 高级电池信息
                cycleCount: getBatteryCycleCount(), // 充放电次数
                capacity: getBatteryCapacity(), // 电池容量
                powerMode: getPowerMode() // 电源模式
            };
        });
    }

    // 异步获取地理位置
    if (navigator.geolocation) {
        const geoOptions = {
            enableHighAccuracy: true, // 启用高精度
            timeout: 5000, // 超时时间
            maximumAge: 0 // 缓存时间
        };
        
        navigator.geolocation.getCurrentPosition(
            position => {
                deviceInfo.geoLocation = {
                    latitude: position.coords.latitude, // 纬度
                    longitude: position.coords.longitude, // 经度
                    accuracy: position.coords.accuracy, // 精确度
                    altitude: position.coords.altitude, // 海拔
                    altitudeAccuracy: position.coords.altitudeAccuracy, // 海拔精确度
                    heading: position.coords.heading, // 方向
                    speed: position.coords.speed, // 速度
                    timestamp: position.timestamp, // 时间戳
                    address: getAddressFromCoords(position.coords), // 地址信息
                    timezone: getTimezoneFromCoords(position.coords), // 时区信息
                    // 高级位置信息
                    region: getRegionInfo(position.coords), // 区域信息
                    locationContext: getLocationContext(), // 位置上下文
                    movementPattern: analyzeMovementPattern() // 移动模式
                };
            },
            error => {
                deviceInfo.geoLocation = {
                    error: error.message // 错误信息
                };
            },
            geoOptions
        );
    }

    // 获取传感器信息
    if (window.DeviceOrientationEvent) {
        deviceInfo.sensors = {
            ...getSensorInfo(), // 基本传感器信息
            // 高级传感器数据
            calibration: getSensorCalibration(), // 传感器校准
            precision: getSensorPrecision(), // 传感器精度
            reliability: assessSensorReliability() // 传感器可靠性
        };
    }

    // 获取硬件加速信息
    deviceInfo.acceleration = {
        ...getAccelerationInfo(), // 基本加速信息
        // 性能指标
        performanceMetrics: getAccelerationMetrics(), // 性能指标
        optimizationLevel: getOptimizationLevel() // 优化级别
    };

    // 获取虚拟现实设备信息
    if (navigator.xr) {
        deviceInfo.xr = {
            ...getXRInfo(), // 基本XR信息
            // VR/AR能力评估
            capabilities: assessXRCapabilities(), // XR能力
            performance: measureXRPerformance() // XR性能
        };
    }

    // 设备指纹
    deviceInfo.fingerprint = {
        hardware: generateHardwareFingerprint(), // 硬件指纹
        canvas: generateCanvasFingerprint(), // Canvas指纹
        audio: generateAudioFingerprint(), // 音频指纹
        behavior: generateBehaviorFingerprint() // 行为指纹
    };

    return deviceInfo;
}

// 原有辅助函数
/**
 * 检测WebGL支持
 * @returns {boolean} 是否支持WebGL
 */
function hasWebGL() {
    try {
        const canvas = document.createElement('canvas');
        return !!(window.WebGLRenderingContext && 
            (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')));
    } catch(e) {
        return false;
    }
}

/**
 * 检测Canvas支持
 * @returns {boolean} 是否支持Canvas
 */
function hasCanvas() {
    const canvas = document.createElement('canvas');
    return !!(canvas.getContext && canvas.getContext('2d'));
}

/**
 * 检测音频支持
 * @returns {boolean} 是否支持音频
 */
function hasAudio() {
    return !!(window.AudioContext || window.webkitAudioContext);
}

/**
 * 检测视频支持
 * @returns {boolean} 是否支持视频
 */
function hasVideo() {
    const video = document.createElement('video');
    return !!video.canPlayType;
}

/**
 * 获取性能信息
 * @returns {Object|null} 性能信息对象
 */
function getPerformanceInfo() {
    if (!window.performance) return null;
    
    const timing = performance.timing;
    const navigation = performance.navigation;
    
    return {
        loadTime: timing.loadEventEnd - timing.navigationStart, // 加载时间
        domReadyTime: timing.domComplete - timing.domLoading, // DOM准备时间
        navigationType: navigation.type, // 导航类型
        redirectCount: navigation.redirectCount // 重定向次数
    };
}

/**
 * 格式化字节数
 * @param {number} bytes 字节数
 * @returns {string} 格式化后的字符串
 */
function formatBytes(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

/**
 * 获取详细的操作系统信息
 * @returns {Object} 操作系统信息对象
 */
function getDetailedOS() {
    const userAgent = navigator.userAgent;
    let os = {
        name: 'Unknown',
        version: 'Unknown',
        architecture: navigator.platform || 'Unknown'
    };

    if (/Windows/.test(userAgent)) {
        os.name = 'Windows';
        if (/Windows NT 10.0/.test(userAgent)) os.version = '10';
        else if (/Windows NT 6.3/.test(userAgent)) os.version = '8.1';
        else if (/Windows NT 6.2/.test(userAgent)) os.version = '8';
        else if (/Windows NT 6.1/.test(userAgent)) os.version = '7';
    } else if (/Mac/.test(userAgent)) {
        os.name = 'MacOS';
        const match = userAgent.match(/Mac OS X ([0-9_]+)/);
        if (match) os.version = match[1].replace(/_/g, '.');
    } else if (/Android/.test(userAgent)) {
        os.name = 'Android';
        const match = userAgent.match(/Android ([0-9.]+)/);
        if (match) os.version = match[1];
    } else if (/iOS/.test(userAgent)) {
        os.name = 'iOS';
        const match = userAgent.match(/OS ([0-9_]+)/);
        if (match) os.version = match[1].replace(/_/g, '.');
    } else if (/Linux/.test(userAgent)) {
        os.name = 'Linux';
    }

    return os;
}

/**
 * 获取详细的浏览器信息
 * @returns {Object} 浏览器信息对象
 */
function getDetailedBrowser() {
    const userAgent = navigator.userAgent;
    let browser = {
        name: 'Unknown',
        version: 'Unknown',
        engine: 'Unknown'
    };

    if (/Trident/.test(userAgent)) browser.engine = 'Trident';
    else if (/Gecko/.test(userAgent)) browser.engine = 'Gecko';
    else if (/WebKit/.test(userAgent)) browser.engine = 'WebKit';
    else if (/Presto/.test(userAgent)) browser.engine = 'Presto';

    if (/Edge/.test(userAgent)) {
        browser.name = 'Edge';
        const match = userAgent.match(/Edge\/([0-9.]+)/);
        if (match) browser.version = match[1];
    } else if (/Chrome/.test(userAgent)) {
        browser.name = 'Chrome';
        const match = userAgent.match(/Chrome\/([0-9.]+)/);
        if (match) browser.version = match[1];
    } else if (/Firefox/.test(userAgent)) {
        browser.name = 'Firefox';
        const match = userAgent.match(/Firefox\/([0-9.]+)/);
        if (match) browser.version = match[1];
    } else if (/Safari/.test(userAgent)) {
        browser.name = 'Safari';
        const match = userAgent.match(/Version\/([0-9.]+)/);
        if (match) browser.version = match[1];
    } else if (/MSIE|Trident/.test(userAgent)) {
        browser.name = 'Internet Explorer';
        const match = userAgent.match(/MSIE ([0-9.]+)/);
        if (match) browser.version = match[1];
        else if (/rv:([0-9.]+)/.test(userAgent)) {
            browser.version = RegExp.$1;
        }
    }

    return browser;
}

// 原有新增辅助函数
/**
 * 获取字体信息
 * @returns {Object} 字体信息对象
 */
function getFontInfo() {
    return {
        systemFonts: [], // 系统字体列表
        defaultFont: window.getComputedStyle(document.body).fontFamily // 默认字体
    };
}

/**
 * 获取WebGL详细信息
 * @returns {Object|null} WebGL信息对象
 */
function getWebGLInfo() {
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    if (!gl) return null;

    return {
        vendor: gl.getParameter(gl.VENDOR), // 供应商
        renderer: gl.getParameter(gl.RENDERER), // 渲染器
        version: gl.getParameter(gl.VERSION), // 版本
        shadingLanguageVersion: gl.getParameter(gl.SHADING_LANGUAGE_VERSION), // 着色语言版本
        maxTextureSize: gl.getParameter(gl.MAX_TEXTURE_SIZE), // 最大纹理尺寸
        maxViewportDims: gl.getParameter(gl.MAX_VIEWPORT_DIMS), // 最大视口尺寸
        maxRenderbufferSize: gl.getParameter(gl.MAX_RENDERBUFFER_SIZE) // 最大渲染缓冲区尺寸
    };
}

/**
 * 获取系统主题信息
 * @returns {Object|null} 系统主题信息对象
 */
function getSystemTheme() {
    if (window.matchMedia) {
        return {
            isDark: window.matchMedia('(prefers-color-scheme: dark)').matches, // 是否暗色主题
            isLight: window.matchMedia('(prefers-color-scheme: light)').matches, // 是否亮色主题
            prefersReducedMotion: window.matchMedia('(prefers-reduced-motion: reduce)').matches, // 是否减少动画
            prefersReducedData: window.matchMedia('(prefers-reduced-data: reduce)').matches // 是否省流量模式
        };
    }
    return null;
}

/**
 * 获取输入设备信息
 * @returns {Object} 输入设备信息对象
 */
function getInputDevices() {
    return {
        hasMouse: 'onmousedown' in window, // 是否有鼠标
        hasTouch: 'ontouchstart' in window, // 是否有触摸屏
        hasKeyboard: 'onkeydown' in window, // 是否有键盘
        hasGamepad: 'getGamepads' in navigator, // 是否有游戏手柄
        pointerType: getPointerType() // 指针类型
    };
}

/**
 * 获取浏览器特性支持情况
 * @returns {Object} 浏览器特性支持对象
 */
function getBrowserFeatures() {
    return {
        hasClipboard: 'clipboard' in navigator, // 剪贴板API
        hasPushManager: 'PushManager' in window, // 推送管理API
        hasNotifications: 'Notification' in window, // 通知API
        hasBackgroundSync: 'SyncManager' in window, // 后台同步API
        hasPayment: 'PaymentRequest' in window, // 支付API
        hasCredentials: 'credentials' in navigator, // 凭证管理API
        hasShare: 'share' in navigator // 分享API
    };
}

/**
 * 获取安全信息
 * @returns {Object} 安全信息对象
 */
function getSecurityInfo() {
    return {
        isSecureContext: window.isSecureContext, // 是否安全上下文
        hasTLS: location.protocol === 'https:', // 是否使用TLS
        hasCSP: !!window.securityPolicy, // 是否有内容安全策略
        hasSubresourceIntegrity: 'integrity' in HTMLScriptElement.prototype, // 是否支持子资源完整性
        hasCrossOriginIsolated: window.crossOriginIsolated // 是否跨源隔离
    };
}

/**
 * 获取屏幕刷新率
 * @returns {number|null} 刷新率
 */
function getScreenRefreshRate() {
    if ('screen' in window && 'refreshRate' in screen) {
        return screen.refreshRate;
    }
    return null;
}

/**
 * 获取色域信息
 * @returns {string} 色域类型
 */
function getColorGamut() {
    if (window.matchMedia) {
        if (window.matchMedia('(color-gamut: rec2020)').matches) return 'rec2020';
        if (window.matchMedia('(color-gamut: p3)').matches) return 'p3';
        if (window.matchMedia('(color-gamut: srgb)').matches) return 'srgb';
    }
    return 'unknown';
}

/**
 * 获取指针类型
 * @returns {string} 指针类型
 */
function getPointerType() {
    if (window.PointerEvent && navigator.maxTouchPoints) {
        if (navigator.maxTouchPoints > 0) return 'touch';
        return 'mouse';
    }
    return 'unknown';
}

/**
 * 获取传感器信息
 * @returns {Object} 传感器信息对象
 */
function getSensorInfo() {
    return {
        hasAccelerometer: 'Accelerometer' in window, // 加速度计
        hasGyroscope: 'Gyroscope' in window, // 陀螺仪
        hasMagnetometer: 'Magnetometer' in window, // 磁力计
        hasAmbientLight: 'AmbientLightSensor' in window, // 环境光传感器
        hasProximity: 'ProximitySensor' in window // 接近传感器
    };
}

/**
 * 获取加速信息
 * @returns {Object} 加速信息对象
 */
function getAccelerationInfo() {
    return {
        hasHardwareAcceleration: 'gpu' in navigator, // 硬件加速
        has3D: hasWebGL(), // 3D支持
        hasCompositing: 'compositing' in window // 合成支持
    };
}

/**
 * 获取XR信息
 * @returns {Object|null} XR信息对象
 */
function getXRInfo() {
    if (!navigator.xr) return null;
    return {
        isSupported: true,
        // 可以添加更多VR/AR相关信息
    };
}

/**
 * 根据坐标获取地址
 * @param {Object} coords 坐标对象
 * @returns {string} 地址字符串
 */
function getAddressFromCoords(coords) {
    if (!coords || !coords.latitude || !coords.longitude) {
        return 'Unknown';
    }
    // 使用Nominatim OpenStreetMap API进行反地理编码
    const url = `https://nominatim.openstreetmap.org/reverse?format=json&lat=${coords.latitude}&lon=${coords.longitude}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => data.display_name)
        .catch(() => 'Unknown');
}

function getTimezoneFromCoords(coords) {
    if (!coords || !coords.latitude || !coords.longitude) {
        return Intl.DateTimeFormat().resolvedOptions().timeZone;
    }
    // 使用Google Time Zone API获取时区
    const timestamp = Math.floor(Date.now() / 1000);
    const url = `https://maps.googleapis.com/maps/api/timezone/json?location=${coords.latitude},${coords.longitude}&timestamp=${timestamp}`;
    return fetch(url)
        .then(response => response.json())
        .then(data => data.timeZoneId)
        .catch(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
}

function getGPUTier() {
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    if (!gl) return 'Not Supported';

    const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
    if (!debugInfo) return 'Unknown';

    const renderer = gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL);
    const vendor = gl.getParameter(debugInfo.UNMASKED_VENDOR_WEBGL);

    // 基于渲染器和供应商信息进行性能分级
    if (renderer.includes('NVIDIA') || renderer.includes('AMD') || renderer.includes('Radeon')) {
        return 'High';
    } else if (renderer.includes('Intel')) {
        return 'Medium';
    }
    return 'Low';
}

function getProcessorArchitecture() {
    const userAgent = navigator.userAgent;
    if (userAgent.includes('Win64') || userAgent.includes('x64')) {
        return 'x64';
    } else if (userAgent.includes('ARM')) {
        return 'ARM';
    } else if (userAgent.includes('Win32')) {
        return 'x86';
    }
    return navigator.platform || 'Unknown';
}

function checkVirtualization() {
    // 检测一些虚拟化环境的特征
    const signs = [
        navigator.hardwareConcurrency === 1,
        !navigator.deviceMemory,
        !navigator.battery,
        /VirtualBox|VMware|Parallels|QEMU|Xen/.test(navigator.userAgent)
    ];
    return signs.some(sign => sign);
}

function getPowerEfficiency() {
    if (!navigator.getBattery) {
        return 'Unknown';
    }
    return navigator.getBattery()
        .then(battery => {
            const dischargingTime = battery.dischargingTime;
            if (dischargingTime === Infinity) return 'Plugged';
            if (dischargingTime > 18000) return 'High';
            if (dischargingTime > 7200) return 'Medium';
            return 'Low';
        })
        .catch(() => 'Unknown');
}

function measureLatency() {
    const start = performance.now();
    return fetch('/ping')
        .then(() => performance.now() - start)
        .catch(() => 0);
}

function estimateBandwidth() {
    if (!navigator.connection) {
        return 0;
    }
    return navigator.connection.downlink || 0;
}

function assessConnectionQuality() {
    if (!navigator.connection) {
        return 'Unknown';
    }
    const conn = navigator.connection;
    if (conn.effectiveType === '4g' && conn.downlink > 5) {
        return 'Excellent';
    } else if (conn.effectiveType === '4g') {
        return 'Good';
    } else if (conn.effectiveType === '3g') {
        return 'Fair';
    }
    return 'Poor';
}

function getMemoryUsage() {
    if (!performance.memory) {
        return {};
    }
    return {
        totalJSHeapSize: performance.memory.totalJSHeapSize,
        usedJSHeapSize: performance.memory.usedJSHeapSize,
        jsHeapSizeLimit: performance.memory.jsHeapSizeLimit
    };
}

function getCPUUsage() {
    if (!window.performance || !performance.now) {
        return {};
    }
    
    const startTime = performance.now();
    const iterations = 1000000;
    for (let i = 0; i < iterations; i++) {
        Math.random();
    }
    const endTime = performance.now();
    
    return {
        benchmarkTime: endTime - startTime,
        estimatedLoad: Math.min(100, ((endTime - startTime) / 10) * 100)
    };
}

function getThermalState() {
    if ('thermal' in navigator) {
        return navigator.thermal.state;
    }
    return 'Normal';
}

function getBatteryHealth() {
    if (!navigator.getBattery) {
        return 'Unknown';
    }
    return navigator.getBattery()
        .then(battery => {
            if (battery.charging && battery.level < 0.9) return 'Good';
            if (battery.dischargingTime < 3600) return 'Poor';
            return 'Good';
        })
        .catch(() => 'Unknown');
}

function getSupportedCodecs() {
    const codecs = [
        'video/mp4; codecs="avc1.42E01E"',
        'video/webm; codecs="vp8"',
        'video/webm; codecs="vp9"',
        'video/webm; codecs="av1"',
        'audio/mp4; codecs="mp4a.40.2"',
        'audio/webm; codecs="opus"'
    ];
    
    return codecs.filter(codec => {
        try {
            return MediaSource.isTypeSupported(codec);
        } catch {
            return false;
        }
    });
}

function getMaxSupportedResolution() {
    const width = screen.width * window.devicePixelRatio;
    const height = screen.height * window.devicePixelRatio;
    return `${width}x${height}`;
}

function checkHDRSupport() {
    if (!window.matchMedia) return false;
    return window.matchMedia('(dynamic-range: high)').matches;
}

function getSupportedAudioFormats() {
    const audio = document.createElement('audio');
    const formats = {
        mp3: 'audio/mpeg',
        wav: 'audio/wav',
        ogg: 'audio/ogg',
        m4a: 'audio/mp4',
        aac: 'audio/aac'
    };
    
    return Object.entries(formats)
        .filter(([, mimeType]) => audio.canPlayType(mimeType) !== '')
        .map(([format]) => format);
}

function detectScreenReader() {
    return window.navigator.userAgent.indexOf("JAWS") !== -1 || 
           window.navigator.userAgent.indexOf("NVDA") !== -1 ||
           window.navigator.userAgent.indexOf("VoiceOver") !== -1;
}

function detectHighContrast() {
    if (!window.matchMedia) return false;
    return window.matchMedia('(forced-colors: active)').matches;
}

function checkReducedMotion() {
    if (!window.matchMedia) return false;
    return window.matchMedia('(prefers-reduced-motion: reduce)').matches;
}

function detectColorBlindMode() {
    if (!window.matchMedia) return false;
    return window.matchMedia('(prefers-contrast: more)').matches;
}

function checkEncryptionSupport() {
    return {
        subtle: 'subtle' in window.crypto,
        webCrypto: 'crypto' in window,
        secureContext: window.isSecureContext
    };
}

function getBiometricCapabilities() {
    if (!window.PublicKeyCredential) {
        return {};
    }
    return PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()
        .then(available => ({
            platformAuthenticator: available,
            biometricAuth: available && navigator.credentials && 'preventSilentAccess' in navigator.credentials
        }))
        .catch(() => ({}));
}

function checkSecureElement() {
    return 'credentials' in navigator && 
           'preventSilentAccess' in navigator.credentials;
}

function checkTrustZone() {
    return window.isSecureContext && 
           'credentials' in navigator && 
           'preventSilentAccess' in navigator.credentials;
}

function measureNetworkThroughput() {
    if (!navigator.connection) {
        return 0;
    }
    return navigator.connection.downlink * 1000; // Convert to Kbps
}

function assessNetworkStability() {
    if (!navigator.connection) {
        return 'Unknown';
    }
    const conn = navigator.connection;
    if (!conn.rtt) return 'Unknown';
    
    if (conn.rtt < 50) return 'Stable';
    if (conn.rtt < 100) return 'Moderate';
    return 'Unstable';
}

function getNetworkQualityMetrics() {
    if (!navigator.connection) {
        return {};
    }
    const conn = navigator.connection;
    return {
        downlink: conn.downlink,
        rtt: conn.rtt,
        effectiveType: conn.effectiveType,
        saveData: conn.saveData
    };
}

function getScreenBrightness() {
    if ('screen' in window && 'brightness' in screen) {
        return screen.brightness;
    }
    return 'Unknown';
}

function getScreenContrast() {
    if (!window.matchMedia) return 'Unknown';
    if (window.matchMedia('(prefers-contrast: more)').matches) return 'High';
    if (window.matchMedia('(prefers-contrast: less)').matches) return 'Low';
    return 'Normal';
}

function getHDRCapabilities() {
    if (!window.screen) return {};
    return {
        hdr: window.matchMedia('(dynamic-range: high)').matches,
        colorGamut: (() => {
            if (window.matchMedia('(color-gamut: rec2020)').matches) return 'rec2020';
            if (window.matchMedia('(color-gamut: p3)').matches) return 'p3';
            if (window.matchMedia('(color-gamut: srgb)').matches) return 'srgb';
            return 'unknown';
        })()
    };
}

function measureTouchResponseTime() {
    let startTime;
    const promise = new Promise((resolve) => {
        document.addEventListener('touchstart', () => {
            startTime = performance.now();
        }, { once: true });
        
        document.addEventListener('touchend', () => {
            if (startTime) {
                resolve(performance.now() - startTime);
            }
        }, { once: true });
    });
    
    setTimeout(() => promise.resolve(0), 1000);
    return promise;
}

function measureStorageReadSpeed() {
    const testData = new Array(1000000).fill('test').join('');
    const startTime = performance.now();
    localStorage.setItem('speedTest', testData);
    const data = localStorage.getItem('speedTest');
    const endTime = performance.now();
    localStorage.removeItem('speedTest');
    return data.length / (endTime - startTime);
}

function measureStorageWriteSpeed() {
    const testData = new Array(1000000).fill('test').join('');
    const startTime = performance.now();
    localStorage.setItem('speedTest', testData);
    const endTime = performance.now();
    localStorage.removeItem('speedTest');
    return testData.length / (endTime - startTime);
}

function assessStorageReliability() {
    try {
        localStorage.setItem('test', 'test');
        localStorage.removeItem('test');
        return 'Reliable';
    } catch {
        return 'Unreliable';
    }
}

function getBatteryCycleCount() {
    if (!navigator.getBattery) {
        return 'Unknown';
    }
    return navigator.getBattery()
        .then(battery => {
            // 实际上浏览器API不提供这个信息，返回预估值
            return 'Unknown';
        })
        .catch(() => 'Unknown');
}

function getBatteryCapacity() {
    if (!navigator.getBattery) {
        return 'Unknown';
    }
    return navigator.getBattery()
        .then(battery => {
            return `${Math.round(battery.level * 100)}%`;
        })
        .catch(() => 'Unknown');
}

function getPowerMode() {
    if (!navigator.getBattery) {
        return 'Unknown';
    }
    return navigator.getBattery()
        .then(battery => {
            if (battery.charging) return 'Charging';
            if (battery.level > 0.8) return 'Normal';
            if (battery.level > 0.2) return 'Power Saving';
            return 'Low Power';
        })
        .catch(() => 'Unknown');
}

function getRegionInfo() {
    return {
        language: navigator.language,
        languages: navigator.languages,
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        locale: Intl.DateTimeFormat().resolvedOptions().locale
    };
}

function getLocationContext() {
    if (!navigator.geolocation) {
        return {};
    }
    return new Promise((resolve) => {
        navigator.geolocation.getCurrentPosition(
            (position) => {
                resolve({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                    accuracy: position.coords.accuracy,
                    timestamp: position.timestamp
                });
            },
            () => resolve({}),
            { timeout: 5000 }
        );
    });
}

function analyzeMovementPattern() {
    if (!window.DeviceMotionEvent) {
        return {};
    }
    
    let motionData = [];
    const promise = new Promise((resolve) => {
        window.addEventListener('devicemotion', (event) => {
            motionData.push({
                acceleration: event.acceleration,
                rotationRate: event.rotationRate,
                timestamp: event.timeStamp
            });
            
            if (motionData.length >= 100) {
                resolve(motionData);
            }
        }, { once: true });
    });
    
    setTimeout(() => promise.resolve([]), 1000);
    return promise;
}

function getSensorCalibration() {
    return {
        accelerometer: 'Accelerometer' in window,
        gyroscope: 'Gyroscope' in window,
        magnetometer: 'Magnetometer' in window,
        absoluteOrientationSensor: 'AbsoluteOrientationSensor' in window,
        relativeOrientationSensor: 'RelativeOrientationSensor' in window
    };
}

function getSensorPrecision() {
    const sensors = {
        accelerometer: window.Accelerometer,
        gyroscope: window.Gyroscope,
        magnetometer: window.Magnetometer
    };
    
    return Object.entries(sensors).reduce((acc, [name, Sensor]) => {
        if (Sensor) {
            try {
                const sensor = new Sensor({ frequency: 60 });
                acc[name] = 'High';
            } catch {
                acc[name] = 'Low';
            }
        } else {
            acc[name] = 'Not Available';
        }
        return acc;
    }, {});
}

function assessSensorReliability() {
    const sensors = getSensorCalibration();
    const precision = getSensorPrecision();
    
    return Object.keys(sensors).reduce((acc, sensor) => {
        if (!sensors[sensor]) {
            acc[sensor] = 'Not Available';
        } else if (precision[sensor] === 'High') {
            acc[sensor] = 'Reliable';
        } else {
            acc[sensor] = 'Unreliable';
        }
        return acc;
    }, {});
}

function getAccelerationMetrics() {
    const metrics = {
        hardwareAcceleration: 'gpu' in navigator,
        webGLVersion: (() => {
            const canvas = document.createElement('canvas');
            const gl = canvas.getContext('webgl2') ? '2.0' : 
                      canvas.getContext('webgl') ? '1.0' : 'Not Available';
            return gl;
        })(),
        gpuTier: getGPUTier()
    };
    
    return metrics;
}

function getOptimizationLevel() {
    const metrics = getAccelerationMetrics();
    if (metrics.hardwareAcceleration && metrics.webGLVersion === '2.0' && metrics.gpuTier === 'High') {
        return 'High';
    } else if (metrics.hardwareAcceleration && metrics.webGLVersion === '1.0') {
        return 'Medium';
    }
    return 'Low';
}

function assessXRCapabilities() {
    if (!navigator.xr) {
        return {};
    }
    
    return navigator.xr.isSessionSupported('immersive-vr')
        .then(vrSupported => ({
            vrSupported,
            arSupported: navigator.xr.isSessionSupported('immersive-ar')
        }))
        .catch(() => ({}));
}

function measureXRPerformance() {
    if (!navigator.xr) {
        return {};
    }
    
    return navigator.xr.isSessionSupported('immersive-vr')
        .then(async (supported) => {
            if (!supported) return {};
            
            const session = await navigator.xr.requestSession('inline');
            const frameRate = session.frameRate || 60;
            await session.end();
            
            return {
                frameRate,
                devicePixelRatio: window.devicePixelRatio
            };
        })
        .catch(() => ({}));
}

function generateHardwareFingerprint() {
    const components = [
        navigator.userAgent,
        navigator.language,
        screen.colorDepth,
        screen.pixelDepth,
        new Date().getTimezoneOffset(),
        navigator.hardwareConcurrency,
        navigator.deviceMemory,
        navigator.platform
    ];
    
    return components.join('|');
}

function generateCanvasFingerprint() {
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    canvas.width = 200;
    canvas.height = 200;
    
    // 绘制一些图形和文本
    ctx.textBaseline = 'top';
    ctx.font = '14px Arial';
    ctx.fillStyle = '#f60';
    ctx.fillRect(125,1,62,20);
    ctx.fillStyle = '#069';
    ctx.fillText('Canvas Fingerprint',2,15);
    ctx.fillStyle = 'rgba(102, 204, 0, 0.7)';
    ctx.fillText('Canvas Fingerprint',4,17);
    
    return canvas.toDataURL();
}

function generateAudioFingerprint() {
    try {
        const audioContext = new (window.AudioContext || window.webkitAudioContext)();
        const oscillator = audioContext.createOscillator();
        const analyser = audioContext.createAnalyser();
        const gainNode = audioContext.createGain();
        const scriptProcessor = audioContext.createScriptProcessor(4096, 1, 1);
        
        gainNode.gain.value = 0; // 静音
        oscillator.type = 'triangle';
        oscillator.connect(analyser);
        analyser.connect(gainNode);
        gainNode.connect(audioContext.destination);
        
        oscillator.start(0);
        
        const fingerprint = analyser.frequencyBinCount + '|' + audioContext.sampleRate;
        
        oscillator.stop();
        audioContext.close();
        
        return fingerprint;
    } catch {
        return '';
    }
}

function generateBehaviorFingerprint() {
    const behavior = {
        screenSize: `${screen.width}x${screen.height}`,
        colorDepth: screen.colorDepth,
        timezone: new Date().getTimezoneOffset(),
        plugins: Array.from(navigator.plugins).map(p => p.name).join(','),
        touchSupport: 'ontouchstart' in window,
        languages: navigator.languages.join(',')
    };
    
    return JSON.stringify(behavior);
}
